/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.manchini.stereocv.telas;

import br.com.manchini.stereocv.utils.CamResolucao;
import br.com.manchini.stereocv.utils.ImgUtils;
import com.googlecode.javacv.CanvasFrame;
import com.googlecode.javacv.FrameGrabber;
import com.googlecode.javacv.OpenCVFrameGrabber;
import static com.googlecode.javacv.cpp.opencv_highgui.cvSaveImage;
import static com.googlecode.javacv.cpp.opencv_core.*;
import javax.swing.DefaultComboBoxModel;


import javax.swing.JOptionPane;

/**
 *
 * @author manchini
 */
public class CapturaImagens extends javax.swing.JDialog {

    private Thread thread;
    private static OpenCVFrameGrabber grabberEsq;
    private static CanvasFrame canvasFrameEsq;
    private static IplImage imgEsq;
    //
    private static OpenCVFrameGrabber grabberDir;
    private static CanvasFrame canvasFrameDir;
    private static IplImage imgDir;
    private boolean capturando;
    private Thread thDir;
    private boolean fotoDir;
    private boolean fotoEsq;

    /**
     * Creates new form ImagemSequencia
     */
    public CapturaImagens(java.awt.Frame parent, boolean modal)  {
        super(parent, modal);
        initComponents();
        
        jComboBox_resolucao.setModel(new DefaultComboBoxModel(CamResolucao.values()));
        jComboBox_resolucao.setSelectedIndex(1);
    }

    private void comecar() {
        if (thread == null) {
            thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    rodar();
                }
            });

            thread.start();
        } else {
            try {
                grabberEsq.stop();
                canvasFrameEsq.dispose();
                thread = null;
            } catch (FrameGrabber.Exception ex) {
                JOptionPane.showMessageDialog(this, "Erro");
                ex.printStackTrace();
            }

        }
    }

    private void rodar() {
        try {
            Integer camEsq = (Integer) jSpinner_esq.getValue();
            Integer camDir = (Integer) jSpinner_dir.getValue();
            CamResolucao camResolucao = (CamResolucao) jComboBox_resolucao.getSelectedItem();
            
            if (camEsq != -1) {

                grabberEsq = new OpenCVFrameGrabber(camEsq);
                grabberEsq.setImageWidth(camResolucao.getW());
                grabberEsq.setImageHeight(camResolucao.getH());
                grabberEsq.start();

                imgEsq = grabberEsq.grab();
                canvasFrameEsq = new CanvasFrame("Cam Esq");
//                jPanel_camesq.add(canvasFrameEsq.getCanvas());
                canvasFrameEsq.setCanvasSize(imgEsq.width(), imgEsq.height());
                canvasFrameEsq.setVisible(true);
                grabberEsq.setFrameRate(grabberEsq.getFrameRate());

                

                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IplImage imgEsqOriginal = null;
                            while ((imgEsqOriginal = grabberEsq.grab()) != null) {

                                if (jCheckBox_Rotaciona.isSelected()) {
                                    ImgUtils.rotacionaImagem(imgEsqOriginal, imgEsq);
                                } else {
                                    imgEsq = imgEsqOriginal;
                                }

                                if (fotoEsq) {
                                    int i = (Integer) jSpinner_Cont.getValue();
                                    cvSaveImage("img/" + i + "esq.jpg", imgEsq);
                                    fotoEsq = false;
                                }
                                IplImage imgFinal = null;
                                if (jCheckBox_tabuleiro.isSelected()) {
                                    imgFinal = ImgUtils.procurarPintaTabuleiro(imgEsq, (Integer) jSpinner_tabx.getValue(), (Integer) jSpinner_taby.getValue());
                                }else{
                                    imgFinal = imgEsq;
                                }

                                ImgUtils.desenhaMiraImagem(imgFinal);
                                canvasFrameEsq.showImage(imgFinal);

                            }

                        } catch (Exception ex) {
                            JOptionPane.showMessageDialog(null, "Erro");
                            ex.printStackTrace();
                        }
                    }
                }).start();
            }
            ////


            ///
            if (camDir != -1) {
                grabberDir = new OpenCVFrameGrabber(camDir);
                grabberDir.setImageWidth(camResolucao.getW());
                grabberDir.setImageHeight(camResolucao.getH());
                grabberDir.start();

                imgDir = grabberDir.grab();
                canvasFrameDir = new CanvasFrame("Cam Dir");
//                jPanel_camdir.add(canvasFrameDir.getCanvas());
                canvasFrameDir.setVisible(true);
                canvasFrameDir.setCanvasSize(imgDir.width(), imgDir.height());

                grabberDir.setFrameRate(grabberDir.getFrameRate());
                thDir = new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            IplImage imgDirOriginal = null;

                            while ((imgDirOriginal = grabberDir.grab()) != null) {
                                
                                if (jCheckBox_Rotaciona.isSelected()) {
                                    ImgUtils.rotacionaImagem(imgDirOriginal, imgDir);
                                } else {
                                    imgDir = imgDirOriginal;
                                }

                           
                                if (fotoDir) {
                                    int i = (Integer) jSpinner_Cont.getValue();
                                    cvSaveImage("img/" + i + "dir.jpg", imgDir);
                                    fotoDir = false;
                                }
                                
                                IplImage imgFinal = null;
                                if (jCheckBox_tabuleiro.isSelected()) {
                                    imgFinal = ImgUtils.procurarPintaTabuleiro(imgDir, (Integer) jSpinner_tabx.getValue(), (Integer) jSpinner_taby.getValue());
                                }else{
                                    imgFinal = imgDir;
                                }

                                ImgUtils.desenhaMiraImagem(imgFinal);
                                canvasFrameDir.showImage(imgFinal);

                            }


                        } catch (FrameGrabber.Exception ex) {
                            JOptionPane.showMessageDialog(null, "Erro");
                            ex.printStackTrace();
                        }
                    }
                });
                thDir.start();
            }


        } catch (FrameGrabber.Exception ex) {
            JOptionPane.showMessageDialog(this, "Erro");
            ex.printStackTrace();
        }
    }
   

    private void foto() {

        fotoDir = true;
        fotoEsq = true;

        jSpinner_Cont.getModel().setValue(jSpinner_Cont.getModel().getNextValue());
        
        


    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel_menu = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jSpinner_esq = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        jSpinner_dir = new javax.swing.JSpinner();
        jCheckBox_Rotaciona = new javax.swing.JCheckBox();
        jComboBox_resolucao = new javax.swing.JComboBox();
        jPanel3 = new javax.swing.JPanel();
        jCheckBox_tabuleiro = new javax.swing.JCheckBox();
        jSpinner_tabx = new javax.swing.JSpinner();
        jLabel4 = new javax.swing.JLabel();
        jSpinner_taby = new javax.swing.JSpinner();
        jPanel2 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jSpinner_Cont = new javax.swing.JSpinner();
        jPanel_camesq = new javax.swing.JPanel();
        jPanel_camdir = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jPanel_menu.setLayout(new javax.swing.BoxLayout(jPanel_menu, javax.swing.BoxLayout.Y_AXIS));

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Cameras"));

        jLabel1.setText("Esquerda");
        jPanel1.add(jLabel1);

        jSpinner_esq.setModel(new javax.swing.SpinnerNumberModel(1, -1, 5, 1));
        jPanel1.add(jSpinner_esq);

        jLabel2.setText("Direita");
        jPanel1.add(jLabel2);

        jSpinner_dir.setModel(new javax.swing.SpinnerNumberModel(2, -1, 5, 1));
        jPanel1.add(jSpinner_dir);

        jCheckBox_Rotaciona.setText("Rotaciona Imagem");
        jCheckBox_Rotaciona.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_RotacionaActionPerformed(evt);
            }
        });
        jPanel1.add(jCheckBox_Rotaciona);

        jPanel1.add(jComboBox_resolucao);

        jPanel_menu.add(jPanel1);

        jCheckBox_tabuleiro.setText("Desenha Tabuleiro");
        jCheckBox_tabuleiro.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jCheckBox_tabuleiroActionPerformed(evt);
            }
        });
        jPanel3.add(jCheckBox_tabuleiro);

        jSpinner_tabx.setModel(new javax.swing.SpinnerNumberModel(9, 1, 12, 1));
        jPanel3.add(jSpinner_tabx);

        jLabel4.setText("x");
        jPanel3.add(jLabel4);

        jSpinner_taby.setModel(new javax.swing.SpinnerNumberModel(6, 0, 9, 1));
        jPanel3.add(jSpinner_taby);

        jPanel_menu.add(jPanel3);

        jButton2.setText("ComeÃ§ar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton2);

        jButton1.setText("Foto");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel2.add(jButton1);

        jLabel3.setText("Sequencia");
        jPanel2.add(jLabel3);

        jSpinner_Cont.setModel(new javax.swing.SpinnerNumberModel(0, 0, 1215752191, 1));
        jPanel2.add(jSpinner_Cont);

        jPanel_menu.add(jPanel2);

        getContentPane().add(jPanel_menu, java.awt.BorderLayout.PAGE_START);

        jPanel_camesq.setPreferredSize(new java.awt.Dimension(600, 300));

        javax.swing.GroupLayout jPanel_camesqLayout = new javax.swing.GroupLayout(jPanel_camesq);
        jPanel_camesq.setLayout(jPanel_camesqLayout);
        jPanel_camesqLayout.setHorizontalGroup(
            jPanel_camesqLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );
        jPanel_camesqLayout.setVerticalGroup(
            jPanel_camesqLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 501, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel_camesq, java.awt.BorderLayout.WEST);

        jPanel_camdir.setPreferredSize(new java.awt.Dimension(600, 300));

        javax.swing.GroupLayout jPanel_camdirLayout = new javax.swing.GroupLayout(jPanel_camdir);
        jPanel_camdir.setLayout(jPanel_camdirLayout);
        jPanel_camdirLayout.setHorizontalGroup(
            jPanel_camdirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 600, Short.MAX_VALUE)
        );
        jPanel_camdirLayout.setVerticalGroup(
            jPanel_camdirLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 501, Short.MAX_VALUE)
        );

        getContentPane().add(jPanel_camdir, java.awt.BorderLayout.EAST);

        setSize(new java.awt.Dimension(1297, 669));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        foto();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        comecar();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void jCheckBox_tabuleiroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_tabuleiroActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox_tabuleiroActionPerformed

    private void jCheckBox_RotacionaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jCheckBox_RotacionaActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_jCheckBox_RotacionaActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(CapturaImagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(CapturaImagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(CapturaImagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(CapturaImagens.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                CapturaImagens dialog = new CapturaImagens(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JCheckBox jCheckBox_Rotaciona;
    private javax.swing.JCheckBox jCheckBox_tabuleiro;
    private javax.swing.JComboBox jComboBox_resolucao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel_camdir;
    private javax.swing.JPanel jPanel_camesq;
    private javax.swing.JPanel jPanel_menu;
    private javax.swing.JSpinner jSpinner_Cont;
    private javax.swing.JSpinner jSpinner_dir;
    private javax.swing.JSpinner jSpinner_esq;
    private javax.swing.JSpinner jSpinner_tabx;
    private javax.swing.JSpinner jSpinner_taby;
    // End of variables declaration//GEN-END:variables
}